<template>
  <div class="register-container row-start">
    <div class="width-14">
        <div class="header">广西制造业企业培优育强服务券</div>
        <div class="sub-header">统一身份认证平台</div>
    </div>
    <div class="width-10 col-center register-form">
        <div class="mb20 color-white tl fs18">您好，欢迎登录!</div>
        <el-tabs class="width-10"  v-model="activeTab">
          <el-tab-pane label="账号密码登录" name="passwordLogin">
            <el-form ref="passwordLoginForm" :model="passwordLoginForm" :rules="passwordLoginRules" label-width="0px">
              <el-form-item prop="username">
                <el-input placeholder="请输入手机号" v-model="passwordLoginForm.username" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item prop="password" class="mt10">
                <el-input type="password" placeholder="请输入密码" v-model="passwordLoginForm.password" autocomplete="off" show-password></el-input>
              </el-form-item>
              <el-form-item prop="code" class="mt10">
                <el-input placeholder="请输入图形验证码" v-model="passwordLoginForm.code" autocomplete="off" @keydown.enter.native="submitPasswordLoginForm">
                  <template #append>
                    <img @click="getImgCaptcha" style="cursor: pointer;height:38px" :src="loginCaptchaObj?.img"  />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <div class="fs16" style="color: #FFC20D;">
                  *涉密合同不上线，上线业务不涉密
                </div>
                <div class="tr color-white fs14" style="cursor: pointer;" @click="openDialog">
                  去重置密码
                </div>
                <el-button type="primary" :loading="loginLoading" size="small" class="width-24 mt20" style="background:rgb(89,109,244);border:1px solid rgb(89,109,244)" @click="submitPasswordLoginForm" @keyup.enter="submitPasswordLoginForm">登录</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="验证码登录" name="captchaLogin">
            <el-form ref="phoneLoginForm" :model="phoneLoginForm" :rules="phoneLoginRules" label-width="0px">
              <el-form-item prop="mobile">
                <el-input placeholder="请输入手机号" v-model="phoneLoginForm.mobile" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item prop="smsCode" class="mt10">
                <el-input placeholder="请输入验证码" v-model="phoneLoginForm.smsCode">
                  <template #append>
                    <el-button :disabled="countdown > 0" @click="getSmsCode">{{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code" class="mt10">
                <el-input placeholder="请输入图形验证码" v-model="phoneLoginForm.code" autocomplete="off" @keydown.enter.native="submitphoneLoginForm">
                  <template #append>
                    <img @click="getImgCaptcha" style="cursor: pointer;height:38px" :src="loginCaptchaObj?.img"  />
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
            <el-button type="primary" :loading="loginLoading" size="small" class="width-24 mt20 mb20" style="background:rgb(89,109,244);border:1px solid rgb(89,109,244)" @click="submitphoneLoginForm" @keyup.enter="submitphoneLoginForm" >登录</el-button>
          </el-tab-pane>
        </el-tabs>
        <div class="login-link">
          没有账号? <a @click="goToRegister">立即注册</a>
        </div>
    </div>
      <el-dialog title="请输入图形验证码确认" width="400px" :visible.sync="showPhoneDialog">
        <el-input v-model="imgcode" placeholder="请输入图形验证码">
          <template #append>
            <img @click="getPhoneCaptcha" style="cursor: pointer;height:38px" :src="phoneCaptchaObj?.img"  />
          </template>
        </el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showPhoneDialog = false">取 消</el-button>
          <el-button :loading="confirmLoading" type="primary" @click="getSmsCode">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="重置密码" :visible.sync="forgetPasswordDialog">
        <el-form ref="form" :model="form" :rules="formRuls" label-width="120px" >
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="form.mobile" style="width:80%"></el-input>
          </el-form-item>
          <el-form-item label="输入验证码" prop="smsCode">
            <el-input v-model="form.smsCode" style="width:80%">
                <template #append>
                   <el-button :disabled="countdown > 0" @click="getSmsCode">{{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}</el-button>
                </template>
            </el-input>
          </el-form-item>
          <el-form-item label="输入密码" prop="password">
            <el-input v-model="form.password" type="password" style="width:80%" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="form.confirmPassword" style="width:80%" type="password" show-password></el-input>
          </el-form-item>
          <!-- <el-form-item label="图形验证码" prop="code">
            <el-input v-model="form.code" style="width:80%">
                <template #append>
                  <img @click="getPasswordImgCaptcha" style="cursor: pointer;height:38px" :src="passwordCaptchaObj?.img"  />
                </template>
            </el-input>
          </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="forgetPasswordDialog = false">取 消</el-button>
          <el-button :loading="confirmLoading" type="primary" @click="resetPassword">重置密码</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
import { login, getcode, smsLogin, sendSmsCode,forgetPassword } from '@/api/homeApi'
// 引入setToken方法 
import { setToken } from '@/utils/auth'
export default {
  name: 'RegisterPage',
  data() {
    var validateMobile = (rule, value, callback) => {
      var reg = /^1[3-9]\d{9}$/;
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };
    var validateUsername = (rule, value, callback) => {
      var regUsername = /^[A-Za-z\u4e00-\u9fa5][A-Za-z0-9\u4e00-\u9fa5_]{1,19}$/;
      var regPhone = /^1[3-9]\d{9}$/;
      if (value === '') {
        callback(new Error('请输入用户名或手机号码'));
      } else if (!regUsername.test(value) && !regPhone.test(value)) {
        callback(new Error('用户名以中文或英文字母开头，包含中文、英文字母、数字和下划线，2-20位字符，或者手机号码'));
      } else {
        callback();
      }
    };
    var validatePassword = (rule, value, callback) => {
      var reg = /^\S*(?=\S{8})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*?.])\S*$/;
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (!reg.test(value)) {
        callback(new Error('密码长度8-20位，至少包含1个大写字母，1个小写字母，1个数字和一个特殊符号(!@#$%^&*?.)'));
      } else {
        callback();
      }
    };
    var validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      activeTab: 'passwordLogin',
      countdown: 0,
      passwordLoginForm: {
        username: '',
        password: '',
      },
      phoneLoginForm: {
        mobile: '',
        code: '',
        smsCode: ''
      },
      passwordLoginRules: {
        username: [{ validator: validateUsername,  trigger: 'blur' }],
        password: [{ validator:validatePassword, trigger: 'blur' }],
        code: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }],
      },
      phoneLoginRules: {
        mobile: [{ validator: validateMobile,  trigger: 'blur' }],
        smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        code: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }],
      },
      formRuls: {
        mobile: [{ required: true,validator: validateMobile,  trigger: 'blur' }],
        smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        password: [{required: true, validator:validatePassword, trigger: 'blur' }],
        confirmPassword: [{ required: true,validator: validateConfirmPassword, trigger: 'blur' }],
        code: [{ required: true, message: '请输入图形验证码', trigger: 'blur' }],
      },
      forgetPasswordDialog: false,
      form: {
        mobile: '',
        code: '',
        smsCode: '',
        password: '',
        confirmPassword: '',
      },
      loginCaptchaObj: {
        img: '',
        uuid: ''
      },
      phoneCaptchaObj: {
        img: '',
        uuid: ''
      },
      passwordCaptchaObj:{
        img: '',
        uuid: ''
      },
      imgcode: '',
      showPhoneDialog: false,
      phoneScence: 1,
      loginLoading: false,
      confirmLoading: false
    }
  },
  created() {
    this.getImgCaptcha();
  },
  methods: {
    // 获得默认账号密码登录的图形验证码
    getImgCaptcha() {
      getcode().then(res => {
        this.loginCaptchaObj.img = 'data:image/png;base64,' + res.img;
        this.loginCaptchaObj.uuid = res.uuid;
      });
    },
    getPasswordImgCaptcha() {
      getcode().then(res => {
        this.passwordCaptchaObj.img = 'data:image/png;base64,' + res.img;
        this.passwordCaptchaObj.uuid = res.uuid;
      });
    },
    // 点击忘记密码时的弹窗
    openDialog() {
      this.forgetPasswordDialog = true;
      this.getPasswordImgCaptcha();
    },
    // 忘记密码时点击获取手机验证码按钮
    passworkGetSmsCode() {
      this.$refs.form.validateField('mobile', valid => {
        if (!valid) {
          this.showPhoneDialog = true;
          // 忘记密码的获取短信验证码的场景是3
          this.phoneScence = 3;
          this.getPhoneCaptcha()
        }
      });
    },
    // 获得图形验证码确认弹窗内的图形验证码
    getPhoneCaptcha() {
      getcode().then(res => {
        this.phoneCaptchaObj.img = 'data:image/png;base64,' + res.img;
        this.phoneCaptchaObj.uuid = res.uuid;
      });
    },
    // 图形验证码确认弹窗的确认按键，从而发送短信验证码
    getSmsCode() {
      let mobile = this.forgetPasswordDialog === false ? this.phoneLoginForm.mobile : this.form.mobile;
      // 忘记密码的场景是3，登录的场景是2
      this.phoneScence = this.forgetPasswordDialog === false ? 2 : 3;
      this.confirmLoading = true;
      sendSmsCode({mobile:mobile,scene:this.phoneScence,code:this.imgcode,uuid:this.phoneCaptchaObj.uuid}).then(res => {
        if (res.code === 200) {
          this.$message.success('验证码发送成功！');
          this.showPhoneDialog = false;
          this.countdown = 60;
          const timer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(timer);
            }
          }, 1000);
        }else{
          this.getPhoneCaptcha();
        }
      }).finally(() => {
        this.confirmLoading = false;
      });
    },
    // 忘记密码的接口逻辑
    resetPassword() {
      // 在这里添加你的代码来处理重置密码的逻辑
      this.confirmLoading = true;
      this.form.uuid = this.passwordCaptchaObj.uuid;
      forgetPassword(this.form).then(res => {
        if (res.code === 200) {
          this.$message.success('重置密码成功！');
        }else{
          this.getPasswordImgCaptcha();
        }
      }).finally(() => {
        this.confirmLoading = false;
        this.forgetPasswordDialog = false;
      });
    },
    // 使用账号名和密码登录
    submitPasswordLoginForm() {
      this.$refs.passwordLoginForm.validate((valid) => {
        if (valid) {
          // 提交表单
          this.passwordLoginForm.uuid = this.loginCaptchaObj.uuid;
          this.loginLoading = true;
          login(this.passwordLoginForm).then(res => {
             if (res.code === 200) {
               this.$message.success('登录成功！');
               // 将登录成功的access_token 存入token
               setToken(res.data.access_token);
               this.$router.push({ path: '/index' });
             } else {
               this.getImgCaptcha();
             }
          }).finally(() => {
            this.loginLoading = false;
          });
        } else {
          return false;
        }
      });
    },
    // 使用手机号登录
    submitphoneLoginForm() {
      this.$refs.phoneLoginForm.validate((valid) => {
        if (valid) {
           this.loginLoading = true;
           smsLogin({
              mobile: this.phoneLoginForm.mobile,
              smsCode: this.phoneLoginForm.smsCode,
              code: this.phoneLoginForm.code,
              uuid: this.loginCaptchaObj.uuid
            }).then(res => {
              if (res.code === 200) {
                this.$message.success('登录成功！');
                // 将登录成功的access_token 存入token
                  setToken(res.data.access_token);
                  this.$router.push({ path: '/index' });
              } else {
                this.getImgCaptcha();
              }
            }).finally(() => {
              this.loginLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    // 使用验证码登录时点击获取验证码按钮
    getLoginPhoneCode() {
      this.$refs.phoneLoginForm.validateField('mobile', valid => {
        if (!valid) {
          // 弹出确认图形验证码的弹窗
          this.showPhoneDialog = true;
          // 忘记密码的获取短信验证码的场景是2
          this.phoneScence = 2;
          // 获得弹窗内的图形验证码
          this.getPhoneCaptcha()
        }
      });
    },
    goToRegister(){
      this.$router.push({ path: '/register' });
    },
    gotoHome(){
      this.$router.push({ path: '/' });
    }
  }
}
</script>

<style scoped>
.register-container {
  background-image: url('@/assets/image/login_bg.png');
  height: 100vh;
  background-size: cover;
  position:relative;
}

.logo img {
  margin-left: 30px;
  margin-top: 30px;
}

.header {
  color: white;
  font-weight: bold;
  font-family: 'Microsoft YaHei';
  font-size: 50px;
  margin-bottom: 20px;
  margin-left: 220px;
  margin-top: 220px;
}
.sub-header {
  color: #436AF7;
  font-weight: bold;
  font-family: 'Microsoft YaHei';
  font-size: 30px;
  margin-top: 20px;
  margin-left: 220px;
}


.register-form {
  background: rgba(5,31,84, 0.75);
  border-radius: 8px;
  padding: 0 50px;
}

.el-form-item {
  margin-bottom: 30px;
}
.el-form-item__content{
  line-height: 20px;
}
.login-link {
  text-align: center;
  color: white;
}

.login-link a {
  color: #add8e6;
  cursor: pointer;
}

/deep/.el-tabs__item:not(.is-active) {
  color: white;
}
</style>
